package com.yiren.backstage.communication.api.impl;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.yiren.backstage.communication.api.I4GCommunication;
import com.yiren.backstage.currency.constant.Messages4G;

import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * Created by WANGRONGXIANG
 * on 2022/2/22
 * Describe 4G移动站信息读取实线类
 */
public class Public4GCommunicationApiImpl implements I4GCommunication {

    private Context context;
    private List<String> messages;
    private Handler handler;

    private int step = 0;   //当前执行到了哪一步
    private int times = 0;  //每个指令重复的次数
    private long startTime; //开发发送的时间
    private String preOrder = ""; //上一个指令
    private boolean isStartGet4G;  //是否开始获取4G信息
    private Handler againHandler = new Handler();
    private Runnable againRunnable;

    public Public4GCommunicationApiImpl(Context context) {
        this.context = context;
    }

    @Override
    public void get4GInfo(List<String> messages, Handler handler) {
        this.messages = messages;
        this.handler = handler;
        sendOrderCode(Messages4G.FOURG1);
        new Handler().postDelayed(() -> {
            //5s内无响应,关闭页面
            if (!isStartGet4G) {
                sendMessage(3, "");
                flushThread();
                exit4GModel();
            }
        }, 5000);
    }

    /**
     * 4G移动站透传信息解析
     *
     * @param data
     */
    @Override
    public void analysisReceiver(String data) {
        if (data.contains("AT+READ=YES")) { // 进入读取模式
            isStartGet4G = true;
            startAgainTask();
            stepOrderSleep(1);
            sendOrderCode(Messages4G.FOURG3);
        } else if (data.contains("AT+MODE=CFG_4G")) { // 进入4G透传模式
            stepOrderSleep(2);
            if (messages != null && messages.size() > 0) {
                sendOrderCode(messages.get(0));
            }
        } else if (data.contains("ICCID") || data.contains("VER:") || data.contains("REGDT")) {
            stepOrderSleep(3);
            for (int i = 0; i < messages.size(); i++) {
                if (data.contains(getSimpleName(messages.get(i)))) {
                    messages.remove(i);
                    sendMessage(1, data);
                    if (messages != null && messages.size() > 0) {
                        i = 0;
                        sendOrderCode(messages.get(0));
                    }
                }
            }
            if (messages.size() == 0) {
                sendOrderCode(Messages4G.FOURG4);
            }
        } else if (data.contains("AT+CFG_END")) { // 退入默认模式
            stepOrderSleep(4);
            sendOrderCode(Messages4G.FOURG2);
        } else if (data.contains("AT+READ=NO")) { // 退出读取模式
            step = 5;
            isStartGet4G = false;
            sendMessage(2, "");
            flushThread();
        } else {
            if (step == 3 && messages.size() == 0) {
                step = 4;
                sendOrderCode(Messages4G.FOURG2);
            } else if (step == 4) { //发送退出读取模式
                step = 5;
                isStartGet4G = false;
                flushThread();
            }
        }
    }

    /**
     * 指令间隔
     */
    private void stepOrderSleep(int step) {
        this.step = step;
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果没有4G信号返回，则1.5s重复发送一次指令，如果指令执行两次仍未数据返回，则退出4G读取模式
     */
    private void startAgainTask() {
        againRunnable = new Runnable() {
            @Override
            public void run() {
                if (isStartGet4G) {
                    if (times < 3) {
                        if ((System.currentTimeMillis() - startTime) > 1500) {
                            times++;
                            againSend4GOrder();
                        }
                    } else {
                        exit4GModel();
                    }
                } else {
                    //如果OBD不接受4G信号，则过3秒返回消息
                    if (System.currentTimeMillis() - startTime > 3000) {
                        sendMessage(3, "");
                        flushThread();
                        exit4GModel();
                    }
                }
                againHandler.postDelayed(this, 500);
            }
        };
        againHandler.post(againRunnable);
    }

    /**
     * 重新发送4G指令
     */
    private void againSend4GOrder() {
        switch (step) {
            case 0:
                sendOrderCode(Messages4G.FOURG1);
                break;
            case 1:
                sendOrderCode(Messages4G.FOURG3);
                break;
            case 2:
                if (messages != null && messages.size() > 0) {
                    sendOrderCode(messages.get(0));
                }
                break;
            case 3:
                if (messages != null && messages.size() > 0) {
                    sendOrderCode(messages.get(0));
                } else {
                    sendOrderCode(Messages4G.FOURG4);
                }
                break;
            case 4:
                sendOrderCode(Messages4G.FOURG2);
                break;
            default:
                break;
        }
    }

    /**
     * 退吹4G读取模式
     */
    private void exit4GModel() {
        if (step == 0 || step == 1 || step == 4) {
            sendOrderCode(Messages4G.FOURG2);
        } else if (step == 2 || step == 3) {
            sendOrderCode(Messages4G.FOURG4);
        }
    }

    /**
     * 发送指令
     *
     * @param order
     */
    private void sendOrderCode(String order) {
        if (!TextUtils.equals(preOrder, order)) {
            times = 0;
            preOrder = order;
            try {
                byte[] bytes = (order + "\r\n").getBytes();
                startTime = System.currentTimeMillis();
                SerialCommunicationApiImpl.getInstance(context).writeData(bytes, "", null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param arg1 1：返回透传信息数据 2：读取结束 3：异常结束
     * @param obj
     */
    private void sendMessage(int arg1, String obj) {
        if (null != handler) {
            Message msg = handler.obtainMessage();
            msg.arg1 = arg1;
            if (StringUtils.isNotEmpty(obj)) msg.obj = obj;
            handler.sendMessage(msg);
        }
    }

    /**
     * 获取4G指令的简写
     *
     * @param cmd 例如：adminAT+ICCID?  =》 ICCID
     */
    public String getSimpleName(String cmd) {
        String simpleName;
        if (cmd.endsWith("?")) {
            simpleName = cmd.substring(cmd.indexOf("+") + 1, cmd.length() - 1);
        } else {
            simpleName = cmd.substring(cmd.indexOf("+") + 1);
        }
        return simpleName;
    }

    /**
     * 结束runnable
     */
    private void flushThread() {
        if (againHandler != null && againRunnable != null) {
            againHandler.removeCallbacks(againRunnable);
        }
    }


}
